//
//  SSFotoBrowserCell.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/8/8.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SVProgressHUD

protocol SSFotoBrowserCellDelegate: NSObjectProtocol {
    func fotoBrowserCellZoom(scale: CGFloat)
    func fotoBrowserCellEndZoom(cell: SSFotoBrowserCell, absoluteRect: CGRect)
}

class SSFotoBrowserCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        resetScrollView()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(scrollView)
        contentView.addSubview(indicator)
        scrollView.addSubview(imgView)
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        indicator.translatesAutoresizingMaskIntoConstraints = false
        // scrollView
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": scrollView]))
        // indicator
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        prepareScrollView()
    }
    
    private func prepareScrollView() {
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 5.0
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
    }
    
    private func setupImgView() {
        let size = adjustSize(imgView.image!)
//        print(size)
//        print(scrollView.contentSize)
//        print(scrollView.frame)
//        let h = scrollView.bounds.height
        let h = UIScreen.mainScreen().bounds.height
        if size.height < h {
            let y = (h - size.height) * 0.5
//            print(y)
            imgView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        } else {
            imgView.frame = CGRect(origin: CGPointZero, size: size)
            
        }
        scrollView.contentSize = size
    }
    
    private func adjustSize(image: UIImage) -> CGSize {
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        return CGSize(width: w, height: h)
    }
    
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
        scrollView.zoomScale = 1.0
    }
    
    var imgURL: NSURL? {
        didSet {
            indicator.startAnimating()
            imgView.image = nil
            resetScrollView()
            imgView.sd_setImageWithURL(imgURL) { (image, _, _, _) -> Void in
                self.indicator.stopAnimating()
                if image == nil {
                    SVProgressHUD.showInfoWithStatus("图片下载失败", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                self.setupImgView()
            }
        }
    }
    weak var fotoDelegate: SSFotoBrowserCellDelegate?
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    private lazy var scrollView = UIScrollView()
    lazy var imgView = UIImageView()
}

extension SSFotoBrowserCell: UIScrollViewDelegate {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imgView
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        if scale > 0.8  && scale < 1.0
        {
            resetScrollView()
            var offsetY = (UIScreen.mainScreen().bounds.height - view!.frame.height) * 0.5
            var offsetX = (UIScreen.mainScreen().bounds.width - view!.frame.width) * 0.5
            offsetX = offsetX < 0 ? 0 : offsetX
            offsetY = offsetY < 0 ? 0 : offsetY
            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    //        print(scrollView.contentSize)
            
        }
        let rect = convertRect(imgView.frame, fromCoordinateSpace: scrollView)
//        let cp = convertPoint(view!.frame.origin, fromCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
//        print("rect0---\(rect)")
//        print("convertPoint---\(cp)")
        fotoDelegate?.fotoBrowserCellEndZoom(self, absoluteRect: rect)
    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {
        fotoDelegate?.fotoBrowserCellZoom(imgView.transform.a)
    }
}
